<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Battery extends Model
{
    protected $table = 'xfy_battaries';


    public function settings()
    {
        return $this->hasMany(BatterySetting::class, 'battery_id');
    }

    public static function afterDeleted($id){
        DB::table('xfy_battary_settings')->where('battery_id', $id)->delete();
    }

    public static function setSwitchStatus($huaweiId, $val){
        $battery = self::where('huawei_id', $huaweiId)->first();
        if ($battery) {
            foreach (BatterySetting::LEVEL_TEXT as $level => $text) {
                self::setSwitchByLevel($battery['id'], $level, $val);
            }
        }
        return;
    }

    protected static function setSwitchByLevel($batteryId, $level, $val){
        $setting = BatterySetting::where('battery_id', $batteryId)->where('level', $level)->orderBy('lowest', 'asc')->first();
        if ($val > $setting['lowest']) {
            return;
        }
        if ($setting && $setting['switch_group']) {
            $switchGroup = json_decode($setting['switch_group'], true);
            foreach ($switchGroup as $oneSwitchGroup) {
                $gateway = SwitchModel::find($oneSwitchGroup);
                $switches = SwitchModel::where('pid', $oneSwitchGroup)->where('level', $level)->get()->toArray();
                if ($switches) {
                    foreach ($switches as $oneSwitch) {
                        SwitchModel::setSwitchOff($gateway['machine_code'], $oneSwitch['id'], $oneSwitch['phase'], $oneSwitch['machine_code']);
                        sleep(5);
                    }
                }
            }
        }
        return;
    }
}